package com.qhhc.service.impl;

import com.qhhc.entity.FileInfo;
import com.qhhc.mapper.FileMapper;
import com.qhhc.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class FileServiceImpl implements FileService {

    @Value("${file.upload-dir:uploads}")
    private String uploadDir;
    
    // 注入FileMapper
    @Autowired(required = false)
    private FileMapper fileMapper;
    
    private List<FileInfo> fileInfoList = new ArrayList<>(); // 临时存储，实际项目使用数据库
    
    @Override
    public FileInfo uploadFile(MultipartFile file) {
        try {
            // 创建上传目录
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extension = StringUtils.getFilenameExtension(originalFilename);
            String newFilename = UUID.randomUUID().toString() + (extension != null ? "." + extension : "");
            
            // 保存文件
            Path filePath = uploadPath.resolve(newFilename);
            Files.copy(file.getInputStream(), filePath);
            
            // 创建文件信息
            FileInfo fileInfo = new FileInfo(
                    newFilename,
                    originalFilename,
                    filePath.toString(),
                    file.getSize(),
                    file.getContentType()
            );
            
            // 如果fileMapper不为空，则使用数据库存储
            if (fileMapper != null) {

                fileMapper.insert(fileInfo);
            } else {
                // 模拟数据库保存
                fileInfo.setId((long) (fileInfoList.size() + 1));
                fileInfoList.add(fileInfo);
            }
            
            return fileInfo;
        } catch (IOException e) {
            throw new RuntimeException("无法存储文件", e);
        }
    }

    @Override
    public List<FileInfo> getAllFiles() {
        if (fileMapper != null) {
            return fileMapper.selectAll();
        }
        return fileInfoList;
    }

    @Override
    public FileInfo getFileById(Long id) {
        if (fileMapper != null) {
            return fileMapper.selectById(id);
        }
        return fileInfoList.stream()
                .filter(file -> Objects.equals(file.getId(), id))
                .findFirst()
                .orElse(null);
    }

    @Override
    public boolean deleteFile(Long id) {
        FileInfo fileInfo = getFileById(id);
        if (fileInfo != null) {
            try {
                // 删除物理文件
                Files.deleteIfExists(Paths.get(fileInfo.getFilePath()));
                
                // 从数据库或列表中移除
                if (fileMapper != null) {
                    return fileMapper.deleteById(id) > 0;
                } else {
                    // 从列表中移除
                    fileInfoList = fileInfoList.stream()
                            .filter(file -> !Objects.equals(file.getId(), id))
                            .collect(Collectors.toList());
                    return true;
                }
            } catch (IOException e) {
                throw new RuntimeException("删除文件失败", e);
            }
        }
        return false;
    }

    @Override
    public FileInfo processFile(Long id, String operation, Object params) {
        FileInfo fileInfo = getFileById(id);
        if (fileInfo == null) {
            return null;
        }
        
        try {
            Path filePath = Paths.get(fileInfo.getFilePath());
            Path outputPath;
            
            switch (operation.toLowerCase()) {
                case "rename":
                    if (params instanceof String) {
                        String newName = (String) params;
                        String extension = StringUtils.getFilenameExtension(fileInfo.getOriginalFileName());
                        newName = newName + (extension != null ? "." + extension : "");
                        
                        outputPath = filePath.getParent().resolve(newName);
                        Files.move(filePath, outputPath);
                        
                        fileInfo.setFileName(newName);
                        fileInfo.setFilePath(outputPath.toString());
                        
                        // 更新数据库
                        if (fileMapper != null) {
                            fileMapper.update(fileInfo);
                        }
                    }
                    break;
                    
                case "compress":
                    // 这里简化实现，实际项目应使用压缩库
                    outputPath = Paths.get(fileInfo.getFilePath() + ".zip");
                    // 假设进行压缩操作...
                    // 这里需要实际的压缩实现
                    fileInfo.setFileName(fileInfo.getFileName() + ".zip");
                    fileInfo.setFilePath(outputPath.toString());
                    
                    // 更新数据库
                    if (fileMapper != null) {
                        fileMapper.update(fileInfo);
                    }
                    break;
                    
                case "copy":
                    String newFilename = "copy_" + fileInfo.getFileName();
                    outputPath = filePath.getParent().resolve(newFilename);
                    Files.copy(filePath, outputPath);
                    
                    FileInfo newFileInfo = new FileInfo(
                            newFilename,
                            "copy_" + fileInfo.getOriginalFileName(),
                            outputPath.toString(),
                            Files.size(outputPath),
                            fileInfo.getFileType()
                    );
                    
                    // 保存到数据库或列表
                    if (fileMapper != null) {
                        fileMapper.insert(newFileInfo);
                    } else {
                        newFileInfo.setId((long) (fileInfoList.size() + 1));
                        fileInfoList.add(newFileInfo);
                    }
                    return newFileInfo;
                    
                default:
                    throw new IllegalArgumentException("不支持的操作类型: " + operation);
            }
            
            return fileInfo;
        } catch (IOException e) {
            throw new RuntimeException("处理文件失败", e);
        }
    }

    @Override
    public List<FileInfo> getFiles(int page, int size) {
        PageHelper.startPage(page + 1, size);
        List<FileInfo> fileList = fileMapper.selectAll();
        PageInfo<FileInfo> pageInfo = new PageInfo<>(fileList);
        return pageInfo.getList();
    }

    @Override
    public long getTotalFiles() {
        return fileMapper.selectAll().size();
    }
}